package com.tedu.myfirstspringboot.controller;

import com.tedu.myfirstspringboot.entity.Article;
import com.tedu.myfirstspringboot.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class ArticleController {
    private static File articleDir;

    static{
        articleDir = new File("./articles");
        if(!articleDir.exists()){
            articleDir.mkdirs();
        }
    }

    /**
     * 写文章
     * @param request
     * @param response
     */
    @RequestMapping("/writeArticle")
    public void write(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理用户发布...");
        //1获取用户提交的登录信息
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content = request.getParameter("content");


        File file = new File(articleDir,title+".obj");
        Article article = new Article(title,author,content);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(article);
            System.out.println("文章写出完毕!");
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(title==null||title.trim().isEmpty()||
                author==null||author.trim().isEmpty()){
            //输入信息有误
            try {
                response.sendRedirect("/article_fail.html");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if(file.exists()){
            try (
                    FileInputStream fis = new FileInputStream(file);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ){
                    Article p = (Article) ois.readObject();
                    System.out.println(p);

                    response.sendRedirect("/article_success.html");
                    return;
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }else{
            //登录失败
            try {
                response.sendRedirect("/article_fail.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
